<template>
  <view class="modal-overlay" v-if="visible" @click="handleOverlayClick">
    <view class="modal-container" @click.stop>
      <!-- 弹窗头部 -->
      <view class="modal-header">
        <view class="modal-title">申请售后</view>
        <view class="close-btn" @click="closeModal">
           <text class="delete-btn-text">×</text>
        </view>
      </view>
      
      <!-- 订单信息 -->
      <view class="order-info-section">
        <view class="section-title">订单信息</view>
         <view class="info-row">
          <text class="info-label">订单ID：</text>
          <text class="info-value">{{ orderId }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">订单编号：</text>
          <text class="info-value">{{ orderNumber }}</text>
        </view>
       
      </view>
      
      <!-- 售后内容 -->
      <view class="content-section">
        <view class="section-title">问题描述 <text class="required">*</text></view>
        <textarea 
          class="content-textarea"
          v-model="formData.content"
          placeholder="请详细描述您遇到的问题，以便我们更好地为您处理"
          maxlength="500"
          :show-confirm-bar="false"
        ></textarea>
        <view class="char-count">{{ formData.content.length }}/500</view>
      </view>
      
      <!-- 图片上传 -->
      <view class="upload-section">
        <view class="section-title">上传凭证图片</view>
        <view class="upload-container">
          <view class="image-list">
            <view 
              class="image-item" 
              v-for="(image, index) in formData.images" 
              :key="index"
            >
              <image class="uploaded-image" :src="image" mode="aspectFill"></image>
              <view class="delete-btn" @click="removeImage(index)">
                <text class="delete-text">×</text>
              </view>
            </view>
            <view 
              class="upload-btn" 
              v-if="formData.images.length < 3"
              @click="chooseImage"
            >
              <image class="upload-icon" src="/static/Images/common/Tianjiatupian.png" mode="aspectFit"></image>
              <text class="upload-text">上传图片</text>
            </view>
          </view>
          <view class="upload-tip">最多上传3张图片，支持jpg、png格式</view>
        </view>
      </view>
      
      <!-- 底部按钮 -->
      <view class="modal-footer">
        <view class="btn-group">
          <view class="btn btn-cancel" @click="closeModal">取消</view>
          <view class="btn btn-submit" @click="submitAfterSale" :class="{ disabled: isSubmitting }">{{ isSubmitting ? '提交中...' : '提交申请' }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { indexApi } from '@/utils/api';

export default {
  name: 'AfterSaleModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    orderNumber: {
      type: String,
      default: ''
    },
    orderId: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      formData: {
        content: '',
        images: []
      },
      isSubmitting: false
    };
  },
  methods: {
    // 关闭弹窗
    closeModal() {
      this.$emit('close');
      this.resetForm();
    },
    
    // 点击遮罩层关闭
    handleOverlayClick() {
      this.closeModal();
    },
    
    // 选择图片
    chooseImage() {
      const remainingCount = 3 - this.formData.images.length;
      uni.chooseImage({
        count: remainingCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          try {
            // 显示上传进度
            uni.showLoading({
              title: '上传中...'
            });
            
            // 逐个上传图片
            for (const filePath of res.tempFilePaths) {
              try {
                const uploadedUrl = await indexApi.uploadFile(filePath, 'file');
                this.formData.images.push(uploadedUrl);
              } catch (uploadError) {
                console.error('图片上传失败:', uploadError);
                uni.showToast({
                  title: '图片上传失败',
                  icon: 'none'
                });
              }
            }
          } catch (error) {
            console.error('处理图片失败:', error);
            uni.showToast({
              title: '处理图片失败',
              icon: 'none'
            });
          } finally {
            uni.hideLoading();
          }
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 删除图片
    removeImage(index) {
      this.formData.images.splice(index, 1);
    },
    
    // 表单验证
    validateForm() {
      if (!this.formData.content.trim()) {
        uni.showToast({
          title: '请填写问题描述',
          icon: 'none'
        });
        return false;
      }
      
      if (this.formData.content.trim().length < 10) {
        uni.showToast({
          title: '问题描述至少需要10个字符',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    // 提交售后申请
    async submitAfterSale() {
      if (this.isSubmitting) return;
      
      if (!this.validateForm()) return;
      
      this.isSubmitting = true;
      
      try {
        // 准备提交数据
        const submitData = {
          order_id: this.orderId,
          content: this.formData.content.trim(),
          image: this.formData.images.length > 0 ? this.formData.images[0] : '' // 取第一张图片作为image参数
        };
        
        console.log('AfterSaleModal: 准备提交售后申请', submitData);
        
        // 触发提交事件，由父组件处理API调用
        this.$emit('submit', submitData);
        
        console.log('AfterSaleModal: 已触发submit事件');
        
      } catch (error) {
        console.error('提交售后申请失败:', error);
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        });
        this.isSubmitting = false;
      }
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        content: '',
        images: []
      };
      this.isSubmitting = false;
    }
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal-container {
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-icon {
  width: 16px;
  height: 16px;
}

.order-info-section,
.content-section,
.upload-section {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.required {
  color: #ff4757;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
}

.info-label {
  color: #666;
  width: 80px;
  flex-shrink: 0;
}

.info-value {
  color: #333;
  flex: 1;
}

.content-textarea {
  width: 100%;
  min-height: 100px;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  box-sizing: border-box;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.upload-container {
  width: 100%;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.image-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 20px;
  height: 20px;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.delete-text {
  color: #fff;
  font-size: 14px;
  line-height: 1;
}
.delete-btn-text {
  color: #222;
  font-size: 14px;
  line-height: 1;
}


.upload-btn {
  width: 80px;
  height: 80px;
  border: 2px dashed #d0d0d0;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
}

.upload-icon {
  width: 24px;
  height: 24px;
  margin-bottom: 4px;
}

.upload-text {
  font-size: 12px;
  color: #999;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 12px;
}

.modal-footer {
  padding: 20px;
}

.btn-group {
  display: flex;
  gap: 12px;
}

.btn {
  flex: 1;
  height: 44px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: #666;
}

.btn-submit {
  background-color: #007aff;
  color: #fff;
}

.btn-submit.disabled {
  background-color: #ccc;
  color: #999;
}
</style>